<script setup lang="ts">
import { createRoleUserAPI, getRoleDetailAPI, getTreeListAPI, updateRoleAPI } from '@/apis/system';
import type { AddRoleParams, RoleData } from '@/types/system';
import { ElMessage, type FormInstance, type FormRules, type TreeInstance } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const stepIndex = ref(1)
const addStepIndex = async () => {
  try {
    // 步骤1：统一表单校验
    if (stepIndex.value === 1) {
      await roleFormRef.value?.validate();
    } else if (stepIndex.value === 2) {
      // 步骤2: 遍历树形组件，获取所有选中节点的 key 值
      roleForm.perms = []; // 先初始化空数组
      treeRefs.value?.forEach((treeInstance: TreeInstance) => {
        // 获取选中节点的 key 值
        const arrKeys = treeInstance.getCheckedKeys();
        // 追加到分步表单的数组中
        roleForm.perms.push(arrKeys as any);
      });

      // 步骤3: 设置选中权限
      diabledTreeRefs.value?.forEach((treeInstance: TreeInstance, index) => {
        treeInstance.setCheckedKeys(roleForm.perms[index]);
      });

      // 把二维数组变成扁平化，再判断长度
      if (roleForm.perms.flat().length === 0) {
        return ElMessage.error("请角色的选择权限");
      }
    }
    // 步骤增加
    stepIndex.value++;
  } catch {

  }

}
const smallStepIndex = () => {
  stepIndex.value--
}
// 表单数据
const roleForm = reactive<AddRoleParams>({
  remark: "",
  roleName: "",
  perms: [],
});
// 表单验证规则
const roleRules = reactive<FormRules<typeof roleForm>>({
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
});
// 表单实例，用于统一校验
const roleFormRef = ref<FormInstance>();
const diabledTreeRefs = ref<TreeInstance[]>();
// 树形组件
const treeRefs = ref<TreeInstance[]>();

// 获取所有权限列表 - 树形结构数据
const treeList = ref<RoleData[]>([]);
const getTreeList = async () => {
  const res = await getTreeListAPI();
  treeList.value = res.data;
};

/** 提交表单-新增角色 */
const router = useRouter();
const route = useRoute()
const onSubmit = async () => {
  if (route.query.roleId) {
    await updateRoleAPI({
      ...roleForm,
      roleId: Number(route.query.roleId),
    })
  } else {
    await createRoleUserAPI(roleForm);
  }
  ElMessage.success("保存成功");
  router.back();
};
onMounted(async () => {
 await getTreeList()
  if (route.query.roleId) {
    const res = await getRoleDetailAPI(Number(route.query.roleId));
    // 回显表单数据
    roleForm.roleName = res.data.roleName;
    roleForm.remark = res.data.remark;
    roleForm.perms = res.data.perms;
    // 树形组件设置选择状态
    treeRefs.value?.forEach((treeInstance: TreeInstance, index) => {
      treeInstance.setCheckedKeys(res.data.perms[index]);
    });
  }
})
</script>

<template>
  <div class="add-role">
    <header class="add-header">
      <el-page-header :content="$route.query.roleId ? '编辑角色' : '添加角色'" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="stepIndex">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <div v-show="stepIndex === 1" class="form-container">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form label-width="100px" ref="roleFormRef" class="form-box" :model="roleForm" :rules="roleRules">
            <el-form-item label="角色名称" placeholder="角色名称" prop="roleName">
              <el-input v-model="roleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input type="textarea" v-model="roleForm.remark">

              </el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div v-show="stepIndex === 2" class="form-container">
        <div class="title">权限配置</div>
        <div class="form">
          <div class="tree-wrapper">
            <div v-for="item in treeList" :key="item.id" class="tree-item">
              <div class="tree-title">{{ item.title }}</div>
              <el-tree :data="item.children" ref="treeRefs" show-checkbox node-key="id" highlight-current
                default-expand-all :props="{ label: 'title' }">

              </el-tree>
            </div>

          </div>
        </div>
      </div>
      <div v-show="stepIndex === 3" class="form-container">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ roleForm.roleName }}</div>
            <div class="form-item">角色描述：{{ roleForm.remark }}</div>
            <div class="form-item">角色权限：</div>
            <div class="tree-wrapper">
              <div v-for="item in treeList" :key="item.id" class="tree-item">
                <div class="tree-title">{{ item.title }}</div>
                <el-tree ref="diabledTreeRefs" :data="item.children" show-checkbox default-expand-all node-key="id"
                  :highlight-current="false" :props="{ label: 'title', disabled: () => true }" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button v-if="stepIndex > 1" @click="smallStepIndex">上一步</el-button>
        <el-button v-if="stepIndex < 3" @click="addStepIndex" type="primary">下一步</el-button>
        <el-button v-if="stepIndex === 3" type="primary" @click="onSubmit"> {{ $route.query.roleId ? "确认修改" : "确认添加"
          }}</el-button>
      </div>
    </footer>
  </div>
</template>


<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 30px;
    display: flex;

    .step-container {
      height: 400px;
      width: 200px;
    }

    .form-container {
      flex: 1;
      background-color: #fff;
      overflow-y: auto;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;
        }

        .info {
          font-size: 14px;
          color: #666;

          .form-item {
            margin-bottom: 20px;
          }
        }
      }

      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }

  .tree-wrapper {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .tree-item {
      flex: 1;
      padding: 0px 4px;
      text-align: center;

      .tree-title {
        background: #f5f7fa;
        text-align: center;
        padding: 10px 0;
        margin-bottom: 12px;
      }
    }
  }
}
</style>